package com.example.a24porint;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

public class MainActivity extends AppCompatActivity {

    public Socket socket=null;
    private OutputStream outputStream;
    private InputStream inputStream;
    private EditText etip;
    private EditText etport;
    private EditText accountNumber;
    private EditText accountPassword;
    private String download;
    private Button denglu;
    private Button zhuce;
    private Handler mMainHandler;
    private Button getinf;
    private Button localg;
    private BufferedReader in;
    private ExecutorService mThreadPool;
    private byte[] download_head;
    private String receiveMsg;
    InputStream is;
    ApplicationUtil appUtil =null;
    // 输入流读取器对象
    InputStreamReader isr ;
    BufferedReader br ;
    String response;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100) {
                etip.setText("由Handler发送消息");
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            appUtil.init();
            Socket socket = appUtil.getSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String ippp=etip.getText().toString();
                    int porttt= Integer.valueOf(etport.getText().toString()).intValue();
                    initSocket(ippp,porttt);//这一步已经连上了
                    appUtil.setSocket(socket);
                    outputStream=socket.getOutputStream();
                    appUtil.setOutputStream(outputStream);
                    inputStream=socket.getInputStream();
                    appUtil.setInputStream(inputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
        }).start();

        appUtil=(ApplicationUtil) MainActivity.this.getApplication();
        etip=findViewById(R.id.ipjjj);
        etport=findViewById(R.id.portjjj);
        denglu=findViewById(R.id.button4);
        zhuce=findViewById(R.id.button15);
        accountNumber=findViewById(R.id.accountNumber);
        accountPassword=findViewById(R.id.accountPassword);
        getinf=findViewById(R.id.getinf);
        localg=findViewById(R.id.localg);
        zhuce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,zhucewindoow.class); //切换窗口
                startActivity(i);
            }
        });
        getinf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //appUtil.setSocket(socket);
                Intent i = new Intent(MainActivity.this,waitingroom.class); //切换窗口
                startActivity(i);
            }
        });
        denglu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                initLoginThread();
                    //receiveLoginMsg();
            }
        });
        localg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,localgame.class); //切换窗口
                startActivity(i);
            }
        });
    }
    private void receiveLoginMsg() throws IOException {
        while (true) {                   //步骤三
            if ((receiveMsg = in.readLine()) != null) {
                String login=receiveMsg;
                if(login.charAt(0)=='y')
                {
                    Intent i = new Intent(MainActivity.this,waitingroom.class); //切换窗口
                    //Intent i = new Intent(MainActivity.this,onlinegame.class);
                    startActivity(i);
                    break;
                }
            }
        }
    }
    private void receiveMsg() {
        try {
            while (true) {                                      //步骤三
                if ((receiveMsg = in.readLine()) != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            etip.setText(etip.getText()+receiveMsg);
                        }
                    });
                }
            }
        } catch (IOException e) {
            //Log.e(TAG, "receiveMsg: ");
            //e.printStackTrace();
        }
    }
    private void initLoginThread()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String ippp=etip.getText().toString();
                    String username=accountNumber.getText().toString(),password=accountPassword.getText().toString();
                    //int porttt= Integer.valueOf(etport.getText().toString()).intValue();
                    //该线程执行了获取套接字（已连接），获取输出流，制作字符串，发送四个方法
                    //initSocket(ippp,porttt);//此处写服务端的IP和端口，可以在PC端上看自己的IP是多少，
                    //如果用别的工具看不了IP,可以使用cmd，输入ipconfig查看
                    initStream();
                    initString(username,password);
                    initSend();
                    //appUtil.setSocket(socket);
                    //appUtil.setOutputStream(outputStream);
                    //inputStream=socket.getInputStream();
                    //appUtil.setInputStream(inputStream);
                    in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    //receiveMsg();
                    receiveLoginMsg();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
        }).start();
    }
    private void initSocket(final String host, final int port){

        //该方法用于获取套接字和执行连接操作，
        //只要服务端打开了一般都能连上，注意ip和端口正确即可
        // （还有，有的地方网络环境比较复杂，如果发送不成功，也可以试试用手机热点当AP，记得改IP）
        if(socket!=null)return;
        try {
            socket=new Socket(host,port);//这一步就已经连接上了，
            //与C的区别就是不用建立family，也不用指定连接选型，直接一步到位很方便
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("获取socket",e.toString());
        }

    }

    private void initStream(){
        try {
            outputStream=socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("获取流",e.toString());
        }

    }
    private void initString(String u,String p){
        //download = "TEST BM IT IoT";
        download="login ";
        download+=u;
        for(int i=0;i<20-u.length();i++)
            download+=' ';
        download+=p;
        for(int i=0;i<20-p.length();i++)
            download+=' ';
        /*download+=accountNumber.getText().toString();
        for(int i=0;i<)*/
        download_head = download.getBytes();//要转换成字节数组，也就是byte[]，才允许发送
    }
    private void initSend(){
        String object=null;
        try {
            outputStream.write(download_head);//发送方法就是调用输出流的write，此时数据将会发送到server端
            //accountNumber.setText(br.readLine());
            //Toast ts = Toast.makeText(getBaseContext(),"hahe",Toast.LENGTH_LONG);
            //ts.show();
            // 步骤3：通过输入流读取器对象 接收服务器发送过来的数据
            //accountNumber.setText(inputStream.toString());
            /*byte[] abc = new byte[2015];
            final int ReadBufferLengh;
            ReadBufferLengh=inputStream.read(abc);
            if(ReadBufferLengh!=-1)
            accountNumber.setText(abc.toString());*/
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("发送数据给服务端（输出流）",e.toString());
        }
    }

    public Socket getSocket() {
        return socket;
    }
}

    /*new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    String sss="";
                                    br.readLine();
                                    /*if((sss=br.readLine())!=null)
                                    etip.setText(sss);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }).start();*/
    /*private void initgame()
    {
        String str=getString();
        if(str.charAt(0)=='y') {
            num[0] = (str.charAt(1) - (int) '0') * 10 + str.charAt(2) - (int) '0';
            num[1] = (str.charAt(4) - (int) '0') * 10 + str.charAt(5) - (int) '0';
            num[2] = (str.charAt(7) - (int) '0') * 10 + str.charAt(8) - (int) '0';
            num[3] = (str.charAt(10) - (int) '0') * 10 + str.charAt(11) - (int) '0';
        }
    }*/


    /*private void initThread(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String ippp=etip.getText().toString();
                    int porttt= Integer.valueOf(etport.getText().toString()).intValue();
                    //该线程执行了获取套接字（已连接），获取输出流，制作字符串，发送四个方法
                    initSocket(ippp,porttt);//此处写服务端的IP和端口，可以在PC端上看自己的IP是多少，
                    //如果用别的工具看不了IP,可以使用cmd，输入ipconfig查看
                    initStream();
                    initString();
                    initSend();
                    in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

                    receiveMsg();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
        }).start();
    }*/
